from django import forms

from .models import ConsumeRecord, ServeGift


class ServeGiftAdminForm(forms.ModelForm):
    unit = forms.CharField(label="单位", max_length=8, help_text="建议使用最小单位标识")

    class Meta:
        model = ServeGift
        fields = '__all__'


class ConsumeRecordAdminForm(forms.ModelForm):
    # unit = forms.CharField(label="单位", max_length=8, required=False)
    class Meta:
        model = ConsumeRecord
        # fields = '__all__'
        exclude = ('unit', )

    def clean(self):
        cleaned_data = super().clean()
        count = cleaned_data.get('count')
        gift = cleaned_data['gift']
        cleaned_data['unit'] = gift.unit
        if gift.count < count:
            # raise forms.ValidationError(f"领用数量{count}不能大于可用数量{gift.amount()}", code='invalid')
            self.add_error('count', f"领用数量{count}不能大于可用数量{gift.amount()}")
        return cleaned_data
